import store from "@/store"
import { throttle } from '@/utils'
import keymaster from 'keymaster'

const winCtrlMerge = e => `ctrl+${e}`
const winShiftMerge = e => `ctrl+shift+${e}`
const macCtrlMerge = e => `⌘+${e}`
const macShiftMerge = e => `⌘+shift+${e}`
// windows
const winKeyValue = {
  forward: winCtrlMerge('y'),
  forward_new: winShiftMerge('z'),
  back: winCtrlMerge('z'),
  delete: 'delete'
}
// mac
const macKeyValue = {
  forward: macCtrlMerge('y'),
  forward_new: macShiftMerge('z'),
  back: macCtrlMerge('z'),
  delete: macCtrlMerge('backspace')
}

// 处理键盘记录
const keyRecordHandle = () => {
  // 默认赋值
  window.$KeyboardActive = {
    ctrl: false,
    space: false
  }
  document.onkeydown = e => {//NOSONAR
    const { keyCode } = e//NOSONAR
    if (keyCode == 32 && e.target == document.body) e.preventDefault()
    if ([17, 32].includes(keyCode) && window.$KeyboardActive) {
      switch (keyCode) {
        case 17: window.$KeyboardActive.ctrl = true; break
        case 32: window.$KeyboardActive.space = true; break
      }
    }
  }
  document.onkeyup = e => {//NOSONAR
    const { keyCode } = e//NOSONAR
    if (keyCode == 32 && e.target == document.body) e.preventDefault()
    if ([17, 32].includes(keyCode) && window.$KeyboardActive) {
      switch (keyCode) {
        case 17: window.$KeyboardActive.ctrl = false; break
        case 32: window.$KeyboardActive.space = false; break
      }
    }
  }
}

// 初始化监听事件
export const useAddKeyboard = () => {
  const throttleTime = 50
  const switchHandle = (e, key) => {
    switch (key) {
      // 撤回 ct+z
      case e.back:
        keymaster(key, throttle(() => { store.commit('editor/handleUndo') }, throttleTime))
        break
      // 前进 ct+y
      case e.forward:
        keymaster(key, throttle(() => { store.commit('editor/handleRedo') }, throttleTime))
        break
      // 前进 ct+sh+z
      case e.forward_new:
        keymaster(key, throttle(() => { store.commit('editor/handleRedo') }, throttleTime))
        break
      case e.delete:
        keymaster(key, throttle(() => { store.commit('editor/handleRemove') }, throttleTime))
        break
      default:
        break
    }
  }
  Object.keys(winKeyValue).forEach((key) => {
    switchHandle(winKeyValue, winKeyValue[key])
  })
  Object.keys(macKeyValue).forEach((key) => {
    switchHandle(macKeyValue, macKeyValue[key])
  })
  keyRecordHandle()
}

// 卸载监听事件
export const useRemoveKeyboard = () => {
  document.onkeydown = () => { 
    console.log('onkeydown')
  }
  document.onkeyup = () => { 
    console.log('onkeyup')
  }
  Object.keys(winKeyValue).forEach((key) => {
    keymaster.unbind(winKeyValue[key])
  })
  Object.keys(macKeyValue).forEach((key) => {
    keymaster.unbind(macKeyValue[key])
  })
}